<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">
          {{getTitleByName(nameOfPermission)}}列表查询
          <el-button link @click="delFav()" style="margin-bottom: 5px;" v-if="userFavorites?.length > 0">
            <svg-icon icon-class="stars" color="#E6A23C" />
          </el-button>
          <el-button link @click="addFav()" style="margin-bottom: 5px;" v-else>
            <svg-icon icon-class="star" />
          </el-button>
        </div>
        <div>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item prop="noticeType" label="通知类型">
          <el-select v-model="listQuery.noticeType" class="m-2" placeholder="请选择" disabled>
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getDictList('BudgetNoticeType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item prop="noticeTitle" label="通知标题">
          <el-input v-model="listQuery.noticeTitle" placeholder="通知标题" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="budgetYear" label="预算年度">
          <el-date-picker v-model="listQuery.budgetYear" type="year" placeholder="请选择预算年度" value-format="YYYY" />
        </el-form-item>
        <!-- <el-form-item prop="applyType" label="编报类型">
          <el-input v-model="listQuery.applyType" placeholder="编报类型" @keyup.enter="handleFilter" />
        </el-form-item> -->
        <el-form-item label="截止日期">
          <el-date-picker v-model="listQuery.expireDateRange"
                          value-format="YYYY-MM-DD"
                          style="width: 380px"
                          type="daterange"
                          range-separator="-"
                          start-placeholder="截止日期开始"
                          end-placeholder="截止日期结束" />
        </el-form-item>
        <el-form-item prop="publishState" label="发布状态">
          <el-radio-group v-model="listQuery.publishState">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('PublishState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">列表详情</div>
        <div>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
          -->
          <el-button type="primary" icon="Edit" :disabled="!checkAuthByCode('')" @click="handleAdd">
            新增
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="通知类型" prop="noticeType" min-width="160px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <DictTag :dict-list="getDictList('BudgetNoticeType')" :dict-key="row.noticeType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="通知标题" prop="noticeTitle" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.noticeTitle }}</template>
      </el-table-column>
      <!--
      <el-table-column align="center" label="通知内容" prop="noticeContent" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <span v-html="row.noticeContent"></span>
        </template>
      </el-table-column>
      -->
      <el-table-column align="center" label="预算年度" prop="budgetYear" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.budgetYear }}</template>
      </el-table-column>
      <!--
      <el-table-column align="center" label="编报类型" prop="applyType" min-width="105px" show-overflow-tooltip>
        <template v-slot="{row}">{{ row.applyType }}</template>
      </el-table-column>
      -->
      <el-table-column align="center" label="截止日期" prop="expireDate" min-width="105px" show-overflow-tooltip>
        <template v-slot="{row}">{{ row.expireDate?.substring(0, 10) }}</template>
      </el-table-column>
      <el-table-column align="center" label="发布状态" prop="publishState" min-width="105px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('PublishState')" :enum-key="row.publishState" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="通知类型" prop="noticeType">
          <el-select v-model="obj.noticeType" class="m-2" placeholder="请选择" disabled>
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getDictList('BudgetNoticeType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知标题" prop="noticeTitle">
          <el-input v-model="obj.noticeTitle" placeholder="请输入通知标题，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="通知内容" prop="noticeContent">
          <editor v-model="obj.noticeContent" v-model:readOnly="obj.readOnly" />
        </el-form-item>
        <el-form-item label="预算年度" prop="budgetYear">
          <el-date-picker v-model="obj.budgetYear" type="year" placeholder="请选择" value-format="YYYY" />
        </el-form-item>
        <!--
        <el-form-item label="编报类型" prop="applyType">
          <el-input v-model="obj.applyType" placeholder="请输入编报类型，最多输入20个字符" />
        </el-form-item>
        -->
        <el-form-item label="截止日期" prop="expireDate">
          <el-date-picker v-model="obj.expireDate" placeholder="请输入截止日期" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="发布状态" prop="publishState">
          <el-radio-group v-model="obj.publishState">
            <el-radio-button v-for="item in getEnumList('PublishState')" :label="item.key" :key="item.key">{{ item.value }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="附件">
          <FileUpload :isDrag="true" v-model="fileData" v-model:isReadonly="fileuploadReadonly" @uploadedSuccess="uploadedSuccessFn" @fileDelete="fileDeleteFn"></FileUpload>
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime ? obj.createTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime ? obj.updateTime : '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doDelete, doGetDownload} from '@/config/http'
import Upload from "@/views/components/base/uploadAttachment"
import {alertErrorMsg, customValidator, notifySuccess, svc} from '@/config/common'
import editor from "@/components/Editor/index.vue"
import SvgIcon from "@/components/SvgIcon/index.vue";

const emptyObj = {
  noticeType: null, // 通知类型
  noticeTitle: null, // 通知标题
  noticeContent: null, // 通知内容
  budgetYear: null, // 预算年度
  applyType: null, // 编报类型
  expireDate: null, // 截止日期
  publishState: '1', // 发布状态
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null
}

export default {
  name: 'projectNotice_nocache',
  components: {
    SvgIcon,
    Upload,
    editor,
  },
  mixins: [baseConfig],
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      fileData: [], // 字符串数组（附件上传）
      fileuploadReadonly: false,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        noticeType: null,
        noticeTitle: null,
        budgetYear: null,
        applyType: null,
        expireDateStart: null,
        expireDateEnd: null,
        expireDateRange: [], //
        publishState: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        noticeType: [{ required: true, validator: customValidator, min: 0, max: 20, label: '通知类型', trigger: ['blur', 'change'] }],
        noticeTitle: [{ required: true, validator: customValidator, min: 0, max: 200, label: '通知标题', trigger: ['blur', 'change'] }],
        noticeContent: [{ required: true, validator: customValidator, min: 0, max: 0, label: '通知内容', trigger: ['blur', 'change'] }],
        budgetYear: [{ required: true, validator: customValidator, min: 0, max: 4, label: '预算年度', trigger: ['blur', 'change'] }],
        applyType: [{ required: false, validator: customValidator, min: 0, max: 20, label: '编报类型', trigger: ['blur', 'change'] }],
        expireDate: [{ required: true, validator: customValidator, min: 0, max: 0, label: '截止日期', trigger: ['blur', 'change'] }],
        publishState: [{ required: true, validator: customValidator, min: 0, max: 20, label: '发布状态', trigger: ['blur', 'change'] }],
      },
      attachmentList: [],
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    emptyObj.noticeType = this.$route.meta.noticeType
    switch (emptyObj.noticeType) {
      case "1":
        this.nameOfPermission = 'budgetOneNotice'
        break;
      case "2":
        this.nameOfPermission = 'budgetTwoNotice'
        break;
      case "3":
        this.nameOfPermission = 'budgetModifyNotice'
        break;
    }
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    this.listQuery.noticeType = this.$route.meta.noticeType
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery.expireDateStart = ''
      this.listQuery.expireDateEnd = ''
      if (this.listQuery.expireDateRange) {
        this.listQuery.expireDateStart = this.listQuery.expireDateRange[0]
        this.listQuery.expireDateEnd = this.listQuery.expireDateRange[1]
      }
      doGet(this.svc, '/budget-project-notice/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
      this.listQuery.expireDateStart = ''
      this.listQuery.expireDateEnd = ''
      this.listQuery.expireDateRange = []
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    async handleEdit(row) {
      await this.initFileData(row)
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
      this.fileuploadReadonly = false
    },
    async handleView(row) {
      await this.initFileData(row)
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
      this.fileuploadReadonly = true
    },
    async handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
      this.fileuploadReadonly = false
    },
    uploadedSuccessFn(files) {
      this.fileData.push(files)
    },
    async initFileData(row) {
      this.fileData = await doGet(svc, '/budget-project-notice-file/listByField', {field: 'budgetProjectNoticeId', values: row.id}, false)
      console.debug(this.fileData)
    },
    handleExport() {
      doGetDownload(this.svc, '/budget-project-notice/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, '/budget-project-notice/' + row.id, {}).then(_ => {
        notifySuccess('操作成功')
        this.getList()
      })
    },
    fileDeleteFn(data) {
      console.debug('data',data)
      this.fileData.splice(data.index, 1);
      this.obj[`attachment${data.index + 1}Id`] = null
      this.obj[`attachment${data.index + 1}Name`] = ''
      console.debug('this.fileData',this.fileData)
    },
    async doConfirm(formName) {
      if (this.fileData.length > 10) {
        alertErrorMsg('最多添加10个附件，请整理上传的附件')
        return
      }
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      let o = this.obj
      o.files = []
      this.fileData?.map(item => {
        o.files.push({
          attachmentId: item.id,
          attachmentName: item.original,
        })
      })
      console.log('o',o)
      switch (this.dialogType) {
        case "add":
          doPost(this.svc, '/customBudgetProjectNotice/saveBudgetProjectNotice', o).then(() => {
            notifySuccess('新增成功')
            this.getList()
            this.dialogVisible = false
          });
          break;
        case "edit":
          doPost(this.svc, '/customBudgetProjectNotice/modifyBudgetProjectNotice', o).then(() => {
            notifySuccess('修改成功')
            this.getList()
            this.dialogVisible = false
          });
          break;
      }
    },
  }
}
</script>
